/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *
 * Copyright (c) 2008-2011, Salzburg Research. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 * - Redistributions of source code must retain the above copyright notice,
 *   this list of conditions and the following disclaimer.
 * - Redistributions in binary form must reproduce the above copyright notice,
 *   this list of conditions and the following disclaimer in the documentation
 *   and/or other materials provided with the distribution.
 * - Neither the name of the KiWi Project nor the names of its contributors
 *   may be used to endorse or promote products derived from this software
 *   without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 * Contributor(s):
 *  sstroka
 *
 * File Info:
 *   User: sstroka
 *   Date: 2011/02/18
 *   Time: 12:21
 *
 * Project: KiWi2, kiwi-core module
 */

package kiwi.core.webservices.security;

import kiwi.core.api.security.OAuthTokenIssuerService;
import kiwi.core.api.security.TokenManagerService;
import kiwi.core.api.user.UserService;
import kiwi.core.exception.UserExistsException;
import kiwi.core.model.user.KiWiUser;
import org.apache.amber.oauth2.common.message.OAuthResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;

/**
 * AuthenticationWebService.java
 * User: Stephanie Stroka
 * Date: 18.02.2011
 * Time: 12:21:21
 */
@Path("/")
public class AuthenticationWebService {

    private Logger log = LoggerFactory.getLogger(this.getClass());

    @Inject
    private UserService userService;

    @Inject
    private TokenManagerService tokenManagerService;

    @Inject
    private OAuthTokenIssuerService oauthTokenIssuerService;
    
    /**
     * registerUser() registers a new user. Returns status 200 if the registration was successful.
     * Returns status 403 if the registration was not successful, e.g. if
     * a user with the same name already existed.
     * @param username
     * @param password
     * @return
     */
    @Path("/register")
    @POST
    @Produces("text/plain")
    public Response registerUser(
            @FormParam("username") String username,
            @FormParam("password") String password) {
        try {
            KiWiUser user = userService.createUser(username, password);
            return Response.status(Response.Status.OK).build();
        } catch (UserExistsException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            return Response.status(Response.Status.FORBIDDEN)
                    .entity("Cannot create user. User " + username + " already exists")
                    .build();
        }
    }

    /**
     * authorizeUser() validates the given username and password hash against an existing user in the system.
     * If a user could be identified and authenticated, the response status is set to 200 and an OAuth2
     * accessToken, refreshToken and tokenExpiration is returned as JSON message.
     * If no user was found or if the given passwordHash hash did not match the stored passwordHash hash, status
     * 403 is returned. 
     * @param username
     * @param passwordHash
     * @param request
     * @return
     */
    @Path("/login")
    @POST
    @Produces("application/json")
    public Response authorizeUser(
            @FormParam("username") String username,
            @FormParam("password") String passwordHash,
            @Context HttpServletRequest request) {
        log.debug("Trying to authorize user {} ", username);

        if(username == null || passwordHash == null) {
            return Response.status(Response.Status.FORBIDDEN).build();
        }
        
        KiWiUser user;
        user = userService.getUserByLogin(username);

        if(user == null || !user.getPasswordHash().equals(passwordHash)) {
            return Response.status(Response.Status.UNAUTHORIZED).build();
        }

        OAuthResponse r;
        if((r = oauthTokenIssuerService.constructOAuthResponse(request, user)) != null) {
            log.debug(r.getBody());

            if(r.getResponseStatus() != 200) {
                user = userService.getAnonymousUser();
            }
            userService.setCurrentUser(user);

            return Response.status(r.getResponseStatus()).entity(r.getBody()).build();
//            return Response.ok(r.getBody()).build();
        } else {
            return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
        }
    }

    @Path("/refresh")
    @POST
    @Produces("application/json")
    public Response refreshAccessToken(
            @FormParam("grant_type") String grant_type,
            @FormParam("refresh_token") String refresh_token,
            @Context HttpServletRequest request) {

        if(!grant_type.equals("refresh_token")) {
            return Response.status(Response.Status.FORBIDDEN).build();
        }

        log.debug("Refresh token {} ", refresh_token);

        OAuthResponse r;
        if((r = oauthTokenIssuerService.refreshOAuthToken(refresh_token)) != null) {
            log.debug(r.getBody());

            return Response.status(r.getResponseStatus()).entity(r.getBody()).build();
        } else {
            return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
        }
    }

    /**
     * logout() removes the access token of the user from memory.
     * @param token
     * @return
     */
    @Path("/logout")
    @GET
    @Produces("text/plain")
    public Response logout(
            @QueryParam("oauth_token") String token) {
        if(token == null) {
            return Response.status(
                    Response.Status.NOT_ACCEPTABLE)
                    .entity("Please provide an oauth token as GET parameter 'oauth_token'")
                    .build();
        }
        tokenManagerService.removeAccessToken(token);
        tokenManagerService.removeRefreshToken(token);
        return Response.ok("Successfully logged out").build();
    }
}
